<?php

namespace App;

use App\Mailer\UserMailer;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
      'name', 'email', 'password', 'avatar', 'confirmation_token', 'api_token', 'settings'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

	/**
	 * settings字段是json类型
	 * @var array
	 */
	protected $casts = [
		'settings' => 'array'
	];
	/**
	 * @return Setting
	 */
	public function settings()
	{
		return new Setting($this);
	}

	/**
	 * @param $model
	 * @return bool
	 */
    public function owns($model)
    {
    	return $this->id == $model->user_id;
    }

	/**
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function follows()
	{
		return $this->belongsToMany(Question::class, 'user_question')->withTimestamps();
	}

	/**
	 * @param $question
	 * @return mixed
	 */
	public function followThis($question)
	{
		return $this->follows()->toggle($question);
	}

	/**
	 * @param $question
	 * @return mixed
	 */
	public function followed($question)
	{
		return $this->follows()->where('question_id', $question)->count();
	}

	/**
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function followers()
	{
		return $this->belongsToMany(self::class, 'followers', 'follower_id', 'followed_id')->withTimestamps();
	}

	/**
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function followersUser()
	{
		return $this->belongsToMany(self::class, 'followers', 'followed_id', 'follower_id')->withTimestamps();
	}

	/**
	 * @param $user
	 * @return array
	 */
	public function followThisUser($user)
	{
		return $this->followers()->toggle($user);
	}

	/**
	 * @param $token
	 */
    public function sendPasswordResetNotification($token)
    {
	    (new UserMailer())->passwordReset($token, $this->email);
    }

	/**
	 * @return mixed
	 */
	public function messages()
	{
		return $this->hasMany(Message::class, 'to_user_id');
	}
}
